﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GPMS.DbInit
{
    using GPMS.Model;
    using GPMS.BLL;
    using System.Reflection;
    public class AddHelper
    {
        private GPMSDbContainer gpms;
        public AddHelper(GPMSDbContainer g)
        {
            gpms = g;
        }

        /// <summary>
        /// 把mvc数据写到数据库
        /// </summary>
        public void AddMvcImformations()
        {
            Type[] types = Assembly.Load("GPMS.Web").GetTypes();
            Type actionType = typeof(System.Web.Mvc.ActionResult);
            foreach (Type type in types)
            {
                if (type.Namespace == "GPMS.Web.Controllers" && 
                    type.IsSubclassOf(typeof(GPMS.Web.Controllers.BaseController)))
                {
                    
                    Guid id = Guid.NewGuid();
                    ControllerInfo controller = new ControllerInfo()
                    {
                        ControllerName = type.Name.Replace("Controller",""),
                        ControllerID = id,
                        IsDeleted = false,
                        CreateDate = DateTime.Now
                    };
                    if (!gpms.ControllerInfos.Any(c => c.ControllerName == controller.ControllerName))
                    {
                        Console.WriteLine("添加Controller:" + type.Name);
                        gpms.ControllerInfos.AddObject(controller);
                        gpms.SaveChanges();
                    }
                    else
                    {
                        Console.WriteLine("已存在Controller:" + type.Name);
                        id = gpms.ControllerInfos.FirstOrDefault(c => c.ControllerName == controller.ControllerName).ControllerID;
                    }

                    foreach (MethodInfo method in type.GetMethods())
                    {
                        if (Check(method, actionType))
                        {
                            
                            ActionInfo actionInfo = new ActionInfo()
                            {
                                ActionName = method.Name,
                                ControllerID = id,
                                IsDeleted = false,
                                CreateDate = DateTime.Now,
                                ReturnType = method.ReturnType.Name
                            };
                            if (!gpms.ActionInfos.Any(a=>a.ControllerID==id && a.ActionName==actionInfo.ActionName))
                            {
                                Console.WriteLine("添加Action:{0}-{1}", type.Name, method.Name);
                                gpms.ActionInfos.AddObject(actionInfo);
                                gpms.SaveChanges();
                            }
                            else
                            {
                                Console.WriteLine("已存在Action:{0}-{1}--{2}", type.Name, method.Name,method.ReturnType.Name);
                            }
                            
                        }
                    }
                    Console.WriteLine("-----------------------------------------------");

                }
            }
            gpms.SaveChanges();
        }
        public void ShowMvcImformations()
        {
            gpms.ControllerInfos.ToList().ForEach(c =>
                {
                    Console.WriteLine("Controller:" + c.ControllerName);
                    c.ActionInfos.ToList().ForEach(a => 
                    {
                        Console.WriteLine("Action:{0}-{1}----{2}", c.ControllerName, a.ActionName,a.ReturnType);
                    });
                    Console.WriteLine("-----------------------------------------------");
                });
        }

        /// <summary>
        /// 检测方法时候符合标准
        /// </summary>
        /// <param name="method">方法信息</param>
        /// <param name="type">返回类型</param>
        /// <returns></returns>
        static bool Check(MethodInfo method, Type type)
        {
            var returnType = method.ReturnType.FullName 
                == type.FullName;
            var returnBase = false;
            if (method.ReturnType.BaseType != null)
            {
                returnBase = method.ReturnType.BaseType.FullName 
                    == type.FullName;
            }
            //仅当方式是公有的、返回类型与参数相同或返回的类型基类与参数相同
            return method.IsPublic && (returnType || returnBase);
        }


        /// <summary>
        /// 添加Controller信息
        /// </summary>
        /// <param name="controller">Controller's Entity</param>
        /// <returns></returns>
        public ControllerInfo AddController(ControllerInfo controller)
        {
            if (gpms.ControllerInfos.Any(c => c.ControllerName == controller.ControllerName && c.Description == controller.Description))
            {
                Console.WriteLine("数据库中已经添加{0}Controller了", controller.ControllerName);
            }
            else
            {
                gpms.AddToControllerInfos(controller);
                gpms.SaveChanges();
                Console.WriteLine("添加{0}Controller成功", controller.ControllerName);
            }
            return (from c in gpms.ControllerInfos
                    where c.ControllerName == controller.ControllerName &&
                    c.Description == controller.Description
                    select c).FirstOrDefault();
        }

        /// <summary>
        /// 添加Action信息
        /// </summary>
        /// <param name="actions">Action's Entity List</param>
        public void AddActions(List<ActionInfo> actions)
        {
            actions.ForEach(ac =>
            {
                if (gpms.ActionInfos.Any(a =>
                    a.ActionName == ac.ActionName &&
                    a.Description == ac.Description &&
                    a.ControllerID == ac.ControllerID))
                {
                    Console.WriteLine("数据库中已经添加Action - {0} ", ac.ActionName);
                }
                else
                {
                    gpms.AddToActionInfos(ac);
                    gpms.SaveChanges();
                    Console.WriteLine("添加成功Action - {0} ", ac.ActionName);
                }
            });

        }

        public void AddAdmin()
        {
            Guid adminroleid=Guid.NewGuid();
            Role adminrole = new Role()
            {
                IsDeleted = false,
                Display = true,
                IsDefault = false,
                IsMain = true,
                RoleName = "管理员",
                RoleID = adminroleid,
                CreateDate=DateTime.Now
            };
            if (!gpms.Roles.Any(r=>r.RoleName==adminrole.RoleName))
            {
                gpms.Roles.AddObject(adminrole);
                gpms.SaveChanges();

                adminrole = gpms.Roles.FirstOrDefault(r => r.RoleName == adminrole.RoleName);
                gpms.ActionInfos.ToList().ForEach(action => adminrole.ActionInfos.Add(action));
                gpms.SaveChanges();
            }
            else 
            {
                adminrole = gpms.Roles.FirstOrDefault(r => r.RoleName == adminrole.RoleName);
            }
            adminroleid = gpms.Roles.FirstOrDefault(r => r.RoleName == adminrole.RoleName).RoleID;

            Guid adminid=Guid.NewGuid();
            UserInfo admin = new UserInfo()
            {
                CreateDate = DateTime.Now,
                IsDeleted = false,
                SpecialtyID = gpms.Specialties.FirstOrDefault(s=>s.SpecialtyName == "网络系").SpecialtyID,
                UserID = adminid,
                Email = "admin@sise.com",
                IsLocked = false,
                Password = "00000",
                UserName = "admin"
            };
            if (!gpms.UserInfos.Any(u=>u.UserName==admin.UserName))
            {
                gpms.UserInfos.AddObject(admin);
                gpms.SaveChanges();
                admin = gpms.UserInfos.FirstOrDefault(u => u.UserName == admin.UserName);
                admin.Roles.Add(adminrole);
                gpms.SaveChanges();
            }
            else if (!gpms.UserInfos.Any(u => u.Roles.Any(r=>r.RoleID==adminrole.RoleID) && u.UserName == admin.UserName))
            {
                admin = gpms.UserInfos.FirstOrDefault(u => u.UserName == admin.UserName);
                admin.Roles.Add(adminrole);
                gpms.SaveChanges();
            }
        }

        public void AddLink()
        {
            
            Link link = new Link()
            {
                CreateDate=DateTime.Now,
                IsDeleted = false,
                LinkID = Guid.NewGuid(),
                LinkType = LinkType.Admin.ToString(),
                LinkName = "连接管理!",
                ActionID = gpms.ActionInfos.FirstOrDefault(a => a.ControllerInfo.ControllerName == "Link" && a.ActionName == "List").ActionID
            };
            if (!gpms.Links.Any(l=>l.LinkName==link.LinkName))
            {
                gpms.Links.AddObject(link);
                gpms.SaveChanges();
            }

            Link desktopAdmin = new Link()
            {
                CreateDate = DateTime.Now,
                IsDeleted = false,
                LinkID = Guid.NewGuid(),
                LinkType = LinkType.DestopIcon.ToString(),
                LinkName = "后台管理",
                Width = 640,
                Height = 480,
                Maxable = true,
                Minable = true,
                Resizeable = true
            };
            if (!gpms.Links.Any(l=>l.LinkName==l.LinkName))
            {
                gpms.Links.AddObject(desktopAdmin);
                gpms.SaveChanges();
            }
        }
    }
}
